import { ElMessage } from 'element-plus';
import axios from 'axios';
import _ from 'lodash-es';
import { clearToken, getToken } from '@/utils/auth';

// 访问前缀（线下）
export const BASE_NAME = import.meta.env.VITE_BASE_NAME_API;
export const BASE_MATTER_MAP_URL = 'http://192.168.2.20/matterServerAlpha/#/login';

// 响应码
export const ResponseSuccessCode = '00000';
export const ResponseCode = [
  {
    code: '00000',
    msg: '操作成功',
  },
  {
    code: 'A0001',
    msg: '未认证',
  },
  {
    cole: 'A0002',
    msg: '无权限',
  },
  {
    code: 'A0003',
    msg: '无效token',
  },
  {
    code: 'A0005',
    msg: '用户名不存在',
  },
  {
    code: 'A0004',
    msg: '刷新token与认证token不匹配',
  },
  {
    code: 'A0007',
    msg: '密码错误次数过多,请5分钟后再试',
  },
  {
    code: 'A0006',
    msg: '密码不正确',
  },
  {
    code: 'A1001',
    msg: '用户名已存在',
  },
  {
    code: 'A0101',
    msg: '参数错误',
  },
  {
    code: 'A1003',
    msg: '用户不存在',
  },
  {
    code: 'A1002',
    msg: '手机号已存在',
  },
  {
    code: 'A1101',
    msg: '角色不存在',
  },
  {
    code: 'A1102',
    msg: '存在用户绑定了角色，无法删除',
  },
  {
    code: 'A1202',
    msg: '',
  },
  {
    code: 'A1201',
    msg: '权限不存在',
  },
  {
    code: 'A1004',
    msg: '原密码不正确',
  },
];

const http = axios.create({
  // timeout: 5000,
});

// 文件上传头
export const getFileHeaders = () => {
  return {
    Authorization: getToken() ? `Bearer ${getToken()}` : '',
    'CUSTOMIZE-CLIENT-TYPE': 'web',
  };
};

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 接口带token
    config.headers.Authorization = getToken() ? `Bearer ${getToken()}` : '';

    return config;
  },
  (error) => Promise.reject(error),
);

//  响应拦截器
http.interceptors.response.use(
  (response) => {
    // console.log(response, 'response');

    if (response?.data?.msg === '请求过于频繁，请稍后再试') {
      console.error(response.data.msg);
    }

    return response.data;
  },
  (error) => {
    // console.log(error);

    const responseError = _.find(ResponseCode, (item) => {
      if (item.code === error.response.data.code) {
        return item;
      }
    });

    if (responseError) {
      if (['A0002', 'A0001', 'A0003'].includes(responseError.code)) {
        clearToken();
        ElMessage.error(error.response.data.message);

        setTimeout(() => {
          location.reload();
        }, 1000);
      } else {
        ElMessage.error(error.response.data.message);
      }
    } else {
      return Promise.reject(error.response.data);
    }
  },
);

export default http;
